<!-- 字典管理 -->
<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { Delete, Plus, Search, Refresh, EditPen } from '@element-plus/icons-vue'
import { ElTable } from 'element-plus'
import { formatDate } from '@/utils/dateFormatter';//引入全局日期格式化工具
// 分页
import type { ComponentSize,TableInstance } from 'element-plus'
let PageNum = ref(1)
let pageSize = ref(5)
const size = ref<ComponentSize>('default')
const background = ref(false)
const disabled = ref(false)
const handleSizeChange = (val: number) => {
  getPage();
  console.log(`${val} items per page`)
}
const handleCurrentChange = (val: number) => {
  getPage();
  console.log(`current page: ${val}`)
}
// 主体内容
const tableData = ref([])
// 科室名称：
let name = ref('')
// 状态：
let status = ref('')
let options = [
  {
    value: '0',
    label: '正常',
  }, { 
    value: '1',
    label: '停止',
  }
]
// 字典类型
let type = ref('')
// 创建时间
let date = ref('')
// 默认时间
let defaultTime = ref('')
let total = ref(0)
// 字典编号
let id=ref()
let ids=ref([])
// 查询字典
const getPage = () => {
  http.get('/dict/getPageType', {
    params: {
      pageNum: PageNum.value,
      pageSize: pageSize.value,
      name: name.value,
      status: status.value,
      type: type.value,
      date: date.value,
    }
  }).then((res) => {
    console.log(res)
    tableData.value = res.list
    total.value = res.total
  })
}
// 重置
const chozhi=()=>{
       name.value='';
      status.value='';
      type.value='';
      date.value='';
}
// 窗体加载事件
onMounted(() => {
  getPage()
})


// 添加
let dialogFormVisible = ref(false)
const formLabelWidth = '140px'
const form = ref({
  id: '',
  dictName: '',
  dictType: '',
  status: '0',
  createBy: '',
  createTime: '',
  updateBy: '',
  updateTime: '',
  remark: '',
})
const addDict = () => {
  http.post('/dict/addDictType', form.value).then((res) => {
    if (res > 0) {
      //弹出添加成功消息提示
      ElMessage({
        message: '添加成功',
        type: 'success',
      })
      //清空添加表单数据
      form.value = {
        id: '',
        dictName: '',
        dictType: '',
        status: '',
        createBy: '',
        createTime: '',
        updateBy: '',
        updateTime: '',
        remark: '',
      }
      //关闭对话框
      dialogFormVisible.value = false
      //重新获取当前页的数据
      getPage()
    }
  })
}
// 修改
const upadte = () => {
  http.post('/dict/updateDictType',form.value).then((res)=>{
    if (res > 0) {
      //弹出添加成功消息提示
      ElMessage({
        message: '修改成功',
        type: 'success',
      })
      //清空添加表单数据
      form.value = {
        id: '',
        dictName: '',
        dictType: '',
        status: '',
        createBy: '',
        createTime: '',
        updateBy: '',
        updateTime: '',
        remark: '',
      }
      //关闭对话框
      dialogupdate.value = false
      //重新获取当前页的数据
      getPage()
    }
  })
}
const updateDict = async (index: number, row) => {
  console.log(index, row)
  id.value=row.dictId
  await http.get('/dict/selectId?id='+id.value).then((res)=>{
    form.value=res
  })
  dialogupdate.value= true
}
//删除
import { ElMessage, ElMessageBox } from 'element-plus'
import http from '@/http'
import Cookies from 'universal-cookie';
import { Value } from 'sass-embedded';
import Index from './index.vue';
const open = () => {
  if (ids.value.length === 0) {
    ElMessage.error('请至少选择一个');
    return;
  }
  // 将数组元素用逗号连接成字符串，用于确认框提示
  const idString = ids.value.join(',');
  ElMessageBox.confirm(
    `你是否删除编号为 ${idString} 的字典?`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
   .then(() => {
      // 直接将数组作为请求体发送
      http.post('/dict/deleteDictTypes', ids.value)
     .then((res) => {
        console.log(res);
        if (res > 0) {
          ElMessage({
            type: 'success',
            message: 'Delete completed',
          });
        }
        getPage()
      })
     .catch((error) => {
        console.error('请求出错:', error);
        ElMessage({
          type: 'error',
          message: '删除失败，请稍后重试',
        });
      });
    })
   .catch(() => {
      ElMessage({
        type: 'info',
        message: 'Delete canceled',
      });
    });
};
const datele = () => {

}

interface dict {
  id: number
  date: string
  name: string
  address: string
}

// 表格的元素引用
const multipleTableRef = ref<TableInstance>()
const multipleSelection = ref<number[]>([]) // 存储选中的 deptId

// 获取选中的用户
const handleSelectionChange = (val: dict[]) => {
  console.log("选中的行数据:", val);
  // 使用 map 方法从选中的行数据中提取 deptId，并将这些 deptId 存储在 multipleSelection 数组中
  multipleSelection.value = val.map(row => row.dictId);
  ids.value=multipleSelection.value;
  console.log("选中的 dictId:", multipleSelection.value);
}
//删除
const dateleDict = (index: number, row) => {
  console.log("下表和对象"+index, row)
  ids.value=row.dictId
  console.log("id="+id.value)
  http.post('/dict/deleteDictType',{id:ids.value})
  .then((res)=>{
    console.log(res)
    if(res>0){
      ElMessage({
        type: 'success',
        message: '删除成功',
      }) 
      getPage()
    }  
  })
}
let dialogupdate = ref(false)
</script>

<template>
  <!-- 添加模态框 -->
  <el-dialog v-model="dialogFormVisible" title="添加字典" width="500">
    <el-form :model="form">
      <el-form-item label="字典名称:" :label-width="formLabelWidth">
        <el-input v-model="form.dictName" autocomplete="off" />
      </el-form-item>
      <el-form-item label="字典类型:" :label-width="formLabelWidth">
        <el-input  v-model="form.dictType" autocomplete="off" />
      </el-form-item>
      <el-form-item label="状态:" :label-width="formLabelWidth">
        <el-radio-group v-model="form.status">
          <el-radio value="1">停用</el-radio>
          <el-radio value="0">正常</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="备注:" :label-width="formLabelWidth">
        <el-input v-model="form.remark" style="width: 240px" :rows="2" type="textarea" placeholder="请输入备注" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="addDict()">
          确定
        </el-button>
        <el-button @click="dialogFormVisible = false">取消</el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 修改模态框 -->
  <el-dialog v-model="dialogupdate" title="修改字典" width="500">
    <el-form :model="form">
      <el-form-item label="字典名称:" :label-width="formLabelWidth">
        <el-input v-model="form.dictName" autocomplete="off" />
      </el-form-item>
      <el-form-item label="字典类型:" :label-width="formLabelWidth">
        <el-input   v-model="form.dictType" autocomplete="off" />
      </el-form-item>
      <el-form-item label="状态:" :label-width="formLabelWidth">
        <el-radio-group v-model="form.status">
          <el-radio value="1">停用</el-radio>
          <el-radio value="0">正常</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="备注:" :label-width="formLabelWidth">
        <el-input v-model="form.remark" style="width: 240px" :rows="2" type="textarea" placeholder="请输入备注" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="upadte">
          确定
        </el-button>
        <el-button @click="dialogupdate = false">取消</el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 头部搜索 -->
  <el-row>
    <el-col :span="24">
      字典名称：<el-input v-model="name" style="width: 140px" placeholder="Please input" />
      字典类型：<el-input v-model="type" style="width: 140px" placeholder="Please input" />
      类型:<el-select v-model="status" clearable placeholder="全部" style="width: 140px">
        <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" /></el-select>
      创建时间：
      <el-date-picker
        v-model="date"
        type="date"
        placeholder="Pick a date"
        :default-value="new Date(2010, 9, 1)"
      />
      <el-button :icon="Search" type="primary" @click="getPage">搜索</el-button> <el-button :icon="Refresh" type="primary" @click="chozhi">重置</el-button>
    </el-col>
  </el-row>
  <!-- 添加 修改 删除 -->
  <el-row>
    <el-col :span="14">
      <el-button :icon="Plus" type="primary" @click="dialogFormVisible = true" plain>添加</el-button>
      <!-- <el-button :icon="EditPen" type="success" @click="dialogupdate = true" plain>修改</el-button> -->
      <el-button :icon="Delete" type="danger" @click="open" plain>删除</el-button>
    </el-col>
  </el-row>
  <!--  主体内容-->
  <el-row>
    <el-col :span="24">
        <el-table :data="tableData" style="width: 100%" border stripe ref="multipleTableRef" row-key="dictId"
        @selection-change="handleSelectionChange" v-model="ids">
        <el-table-column type="selection" width="55" />
        <el-table-column label="字典编号" width="120"> 
          <template #default="scope">{{ scope.row.dictId }}</template>
        </el-table-column>
        <el-table-column property="dictName" label="字典名称" width="240" show-overflow-tooltip>
          <template #default="scope">{{ scope.row.dictName }}</template>
        </el-table-column>
        <el-table-column property="dictType" label="字典类型">
          <template #default="scope">{{ scope.row.dictType }}</template>
        </el-table-column>
        <el-table-column property="status" label="状态" width="120">
          <template #default="scope">{{ scope.row.status != 1 ? '正常' : '停用' }}</template>
        </el-table-column>
        <el-table-column property="remark" label="备注" width="240" show-overflow-tooltip>
          <template #default="scope">{{ scope.row.remark }}</template>
        </el-table-column>
        <el-table-column property="createTime" label="创建时间">
          <template #default="scope">{{ formatDate(scope.row.createTime, 'YYYY年MM月DD日 HH:mm') }}</template>
        </el-table-column>
        <el-table-column property="address" label="操作" width="240" show-overflow-tooltip>
          <template #default="scope">
            <el-button :icon="EditPen" type="success" @click="updateDict(scope.$index, scope.row)" plain>修改</el-button>
            <el-button :icon="Delete" type="danger" @click="dateleDict(scope.$index, scope.row)" plain>删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="demo-pagination-block">
        <el-pagination v-model:current-page="PageNum" v-model:page-size="pageSize" :page-sizes="[1, 2, 3]" :size="size"
          :disabled="disabled" :background="background" layout="total, sizes, prev, pager, next, jumper" :total="total"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </el-col>
  </el-row>
</template>

<style scoped>
.demo-pagination-block+.demo-pagination-block {
  margin-top: 10px;
}

.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}

</style>
